﻿using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Lari.Configuration;
//using Lari.Services.Data;
using Lari.Framework.Utility;
using Lari.Services.ViewModel;
using Lari.Web.Utility;
using Lari.Services.Implementation;

namespace Lari.Web.Controllers
{

    public class CoreController : LariController
    {
        private readonly CoreServiceManager _coreMgr;
        private readonly UserManagementManager _userMgr;
        public CoreController(CoreServiceManager coreMngr, UserManagementManager masterMngr)
        {
            _coreMgr = coreMngr;
            _userMgr = masterMngr;
        }

        #region LogOn/LogOff
        public ActionResult LogOn(string returnUrl)
        {
            FormsAuthentication.SignOut();
            if (!string.IsNullOrEmpty(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                AddInfoMessage("Sign in first in order to access requested resource.");
            return View(new UserModel(false) { UserId = "nadeem", Password = "nadeem" });

        }


        [HttpPost]
        public ActionResult LogOnSubmit(UserModel model, string returnUrl)
        {
            try
            {
                var emp = _coreMgr.Logon(model.UserId, model.Password);
                if (emp == null)
                {
                    AddErrorMessage(MessageCode.Core.LogonInvalid);
                    return View(ActionConst.LogOn, model);
                }
                var accessCsv = new StringBuilder();
                if (emp.User.Role != null && emp.User.Role.RoleAccesses != null)
                {
                    foreach (var ra in emp.User.Role.RoleAccesses)
                    {
                        if (ra.IsEnabled)
                            accessCsv.Append(ra.AccessId.ToString(CultureInfo.InvariantCulture) + ",");
                    }

                }

                //var ticket = new FormsAuthenticationTicket(2, model.UserId, DateTime.Now, DateTime.Now.AddDays(1), model.RememberMe, accessCsv.ToString());
                //var encTicket = FormsAuthentication.Encrypt(ticket);
                //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.AddDays(1) });

                var accessCookie = new HttpCookie(CookieName.AccessCsv,
                                                  Encryption.Encrypt(accessCsv.ToString())) { Expires = DateTime.Now.AddDays(1) };
                Response.Cookies.Add(accessCookie);
                FormsAuthentication.SetAuthCookie(model.UserId, model.RememberMe);
                if (!string.IsNullOrEmpty(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction(ApplicationConfig.StartUpAction, ApplicationConfig.StartUpController);



            }
            catch (Exception ex)
            {

                ProcessException(MessageCode.Core.LogonUnhandledError, ex, "CoreController_LogOn");
            }
            return View(ActionConst.LogOn, model);







        }

        //public ActionResult LogOnSubmitCompleted(UserModel model = null, Employee emp = null, string returnUrl = null, Exception ex = null, bool isValidUser = true)
        //{
        //    if (ex != null)
        //    {
        //        ProcessException(MessageCode.Core.LogonUnhandledError, ex, "CoreController_LogOn");

        //    }
        //    if (!isValidUser)
        //    {
        //        AddErrorMessage(MessageCode.Core.LogonUnhandledError);
        //        return View(ActionConst.LogOn, new UserModel(false));
        //    }



        //    if (model != null)
        //    {
        //        var accessCsv = new StringBuilder();
        //        if (emp.User.Role != null && emp.User.Role.RoleAccesses != null)
        //        {
        //            foreach (var ra in emp.User.Role.RoleAccesses)
        //            {
        //                if (ra.IsEnabled)
        //                    accessCsv.Append(ra.AccessId.ToString(CultureInfo.InvariantCulture) + ",");
        //            }

        //        }

        //        //var ticket = new FormsAuthenticationTicket(2, model.UserId, DateTime.Now, DateTime.Now.AddDays(1), model.RememberMe, accessCsv.ToString());
        //        //var encTicket = FormsAuthentication.Encrypt(ticket);
        //        //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.AddDays(1) });

        //        var accessCookie = new HttpCookie(CookieName.AccessCsv,
        //                                          Encryption.Encrypt(accessCsv.ToString())) { Expires = DateTime.Now.AddDays(1) };
        //        Response.Cookies.Add(accessCookie);
        //        FormsAuthentication.SetAuthCookie(model.UserId, model.RememberMe);


        //    }


        //    if (!string.IsNullOrEmpty(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //    {
        //        return Redirect(returnUrl);
        //    }
        //    return RedirectToAction(ApplicationConfig.StartUpAction, ApplicationConfig.StartUpController);

        //}

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            var accessCookieName = Encryption.Encrypt(CookieName.AccessCsv);

            if (Request.Cookies[accessCookieName] != null)
            {
                var myCookie = new HttpCookie(accessCookieName) { Expires = DateTime.Now.AddDays(-1) };
                Response.Cookies.Add(myCookie);
            }
            return RedirectToAction(ActionConst.LogOn, ControllerConst.Core);
        }
        public ActionResult KeepLive()
        {
            return View();
        }
        #endregion

        #region User Profile

        [Authorize]
        public ActionResult UserProfile()
        {
            var model = new UserProfileModel();
            return View(model);
        }
        
       

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult ChangePassword(UserProfileModel model)
        {
            model.UserId = User.Identity.Name;
            try
            {
                if (_userMgr.ValidateUser(model.UserId, model.OldPassword))
                {
                    _userMgr.ChangePassword(model.UserId, model.NewPassword);
                    AddInfoMessage(MessageCode.User.PasswordChangedSuccess);
                }
                else
                {
                    AddErrorMessage(MessageCode.User.InvalidPassword);
                    model.NewPassword = string.Empty;
                    model.ConfirmPassword = string.Empty;

                    return View(ActionConst.ChangePassword, model);
                }
            }
            catch (Exception ex)
            {
                ProcessException(MessageCode.Core.ChangePasswordFailed, ex, "CoreController UserProfileChangePassword ");
            }

            return RedirectToAction(ActionConst.LogOff, ControllerConst.Core);
        }

        public ActionResult ChangeHintQuestion()
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult ChangeHintQuestion(UserProfileModel model)
        {
            try
            {
                model.UserId = User.Identity.Name;
                _userMgr.SaveHintQuestionAnswer(model);
                AddInfoMessage(MessageCode.User.HintQuestionAnswerSuccess);
                return RedirectToAction(ActionConst.LogOff, ControllerConst.Core);
            }
            catch (Exception ex)
            {
                ProcessException(MessageCode.Core.HintQuestionSubmitFailed, ex, "CoreController UserProfileQuestionSubmit ");
            }
            return View(ActionConst.ChangeHintQuestion, model);


        }
       
        #endregion

        public ActionResult SignupUser()
        {
            throw new NotImplementedException();
        }

        public ActionResult ForgotPassword()
        {
            throw new NotImplementedException();
        }


        
    }
}
